import { useUserStore } from '@/hooks';
import { getValidators } from '@/utils/validate';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Http, HttpSource } from '@/utils';
import CryptoJS from 'crypto-js';
import { ElMessage } from 'element-plus';
import { MicroAppStateActions, initGlobalState } from 'qiankun';

export default function () {
    //定义变量控制按钮加载效果
    let loading = ref(false);
    const userInfo = reactive({ userName: '', password: '' })
    const rules = getValidators(['userName', 'password'], 'change')
    const router = useRouter();
    const doLogin = async () => {
        const _password = CryptoJS.SHA256(userInfo.password).toString(CryptoJS.enc.Hex);
        const res = await Http.post(HttpSource.Java, 'login', { userName: userInfo.userName, password: _password })
        if (res?.errorCode === 0 && res.result === 1) {
            const store = useUserStore();
            store.setUserInfo({ ...userInfo, token: _password })
            router.push({ name: 'home' });

            // 初始化 state
            initGlobalState({ userName: userInfo.userName, token: _password });
        } else {
            ElMessage.error(`用户名或密码不正确`)
        }
    }

    return {
        userInfo,
        loading,
        doLogin,
        rules,
    }
}